import {Divider, Popconfirm, Table, DatePicker, Select, TreeSelect} from 'antd'
import React, {useState, useEffect} from 'react'
import styles from "@/pages/Info/Edit/style.less";
import {connect} from 'umi'
import moment from 'moment'
import {jobLevelTypeList} from '@/utils/constant'
import {getPromotion, getJobByOrgId} from '@/pages/Personnel/Promotion/Management/service'
import {findItemByTree} from "@/utils/functions";

const {Option} = Select;

const TableForm = ({userList, tempUnitTree, onChange, jobLevel}) => {
  const [clickedCancel, setClickedCancel] = useState(false);
  const [loading, setLoading] = useState(false);
  const [cacheOriginData, setCacheOriginData] = useState({});
  const [data, setData] = useState([]);
  const [jobList, setJobList] = useState([]);
  const [jobTemp, setJobTemp] = useState([]);
  const [tempJobLevel,setTempJobLevel] = useState([]);

  useEffect(() => {
    setLoading(true);
    if(userList.length < 1){
      setData([])
    }else {
      let newTempData = [];
      userList.forEach((item,index) => {
        getDeptJobList(item.unitId);
        newTempData.push({...item, key:item.code, promotionType:item.promotionType, promotionDate: item.promotionDate || new Date()})
      });
      setData(newTempData);
    }
    setLoading(false);
  }, [userList]);

  const getRowByKey = (key, newData) => (newData || data)?.filter((item) => item.key === key)[0];

  const toggleEditable = (e, key, type) => {
    e.preventDefault();
    const newData = data?.map((item) => ({ ...item }));
    const target = getRowByKey(key, newData);
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        cacheOriginData[key] = { ...target };
        setCacheOriginData(cacheOriginData);
        getDeptJobList(target.unitId);
        if (target.promotionType === 2) {
          setTempJobLevel(jobLevel.filter(e => e.type === 'CODE_MANAGEMENTRANK').reverse());
        } else {
          setTempJobLevel(jobLevel.filter(e => e.type === 'CODE_PROFESSIONALRANK').reverse());
        }
      }
      target.editable = !target.editable;
      if (type === 'save'){
        onChange(newData)
      }else {
        setData(newData);
      }
    }
  };

  const remove = (e, key) => {
    const newData = [...data];
    let dataList = newData.filter(item => item.key !== key);
    onChange(dataList,true);
  };

  const handleFieldChange = (e, fieldName, key) => {
    const newData = [...data];
    const target = getRowByKey(key, newData);
    if (target) {
      target[fieldName] = e.target ? e.target.value : e;
      setData(newData);
      if(fieldName === 'promotionType'){
        if (target.promotionType === 2) {
          setTempJobLevel(jobLevel.filter(e => e.type === 'CODE_MANAGEMENTRANK').reverse());
        } else {
          setTempJobLevel(jobLevel.filter(e => e.type === 'CODE_PROFESSIONALRANK').reverse());
        }
        target.afterJobLevelId = null;
      }
    }
  };

  const getDeptJobList = (id) => {
    let temp = jobTemp;
    getJobByOrgId(id).then((res) => {
      setJobList(res);
      setJobTemp(temp.concat(res));
    })
  };

  const updateRow = (e, rowKey) => {
    e.persist();
    if (clickedCancel) {
      setClickedCancel(false);
      return
    }
    toggleEditable(e, rowKey, 'save');
  };

  const cancel = (e, key) => {
    setClickedCancel(true);
    e.preventDefault();
    const newData = [...data];
    let cacheData = newData.map((item) => {
      if (item.key === key) {
        // 编辑前的原始数据
        if (cacheOriginData[key]) {
          const originItem = { ...cacheOriginData[key], editable: false };
          delete cacheOriginData[key];
          setCacheOriginData(cacheOriginData);
          return originItem
        }
      }
      return item
    });
    onChange(cacheData);
    setClickedCancel(false)
  };

  const columns = [
    {
      title: '工号',
      dataIndex: 'code',
      key: 'code',
      disabled: true,
      width: 110,
      fixed: 'left'
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      disabled: true,
      width: 100,
      fixed: 'left'
    },
    {
      title: '部门',
      dataIndex: 'unitId',
      disabled:true,
      width: 150,
      render:(text) => {
        return  findItemByTree(tempUnitTree,parseInt(text))?.title;
      }
    },
    {
      title: '岗位',
      dataIndex: 'jobId',
      disabled: true,
      width: 150,
      render: (text) => {
        const res = jobTemp.find((item) => item.coidassignedjob === text);
        return res ? res.cname : text
      },
    },
    {
      title:  <><div>降级日期</div><div>（薪酬生效日期）</div></>,
      dataIndex: 'promotionDate',
      key: 'promotionDate',
      width: 150,
      render: (text, record) => {
        if (record.editable) {
          return (
            <DatePicker placeholder="请选择日期" value={moment(text)}
                        onChange={(e) => handleFieldChange(e, 'promotionDate', record.key)}/>
          )
        }
        return moment(text).format('YYYY-MM-DD')
      },
    },
    {
      title: '调转类型',
      dataIndex: 'promotionType',
      key: 'promotionType',
      width: 150,
      render: (text, record) => {
        if (record.editable) {
          return (
            <Select placeholder="请选择" value={text} onChange={(e) => handleFieldChange(e, 'promotionType', record.key)}>
              {jobLevelTypeList.map((item, index) => {
                return (
                  <Option value={item.value} key={item.value}>
                    {item.label}
                  </Option>
                )
              })}
            </Select>
          )
        }
        const res = jobLevelTypeList.find((item) => item.value === parseInt(text))
        return res ? res.label : text
      },
    },
    {
      title: '降级后部门',
      dataIndex: 'unitId',
      disabled:true,
      width: 150,
      render:(text) => {
        return  findItemByTree(tempUnitTree,parseInt(text))?.title;
      }
    },
    {
      title: '降级后岗位',
      dataIndex: 'afterJobId',
      key: 'afterJobId',
      width: 200,
      render: (text, record) => {
        if (record.editable) {
          return (
            <Select placeholder="请选择" value={text} onChange={(e) => handleFieldChange(e, 'afterJobId', record.key)}>
              {jobList.map((item, index) => {
                return (
                  <Option value={`${item.coidassignedjob}`} key={item.coidassignedjob}>
                    {item.cname}
                  </Option>
                )
              })}
            </Select>
          )
        }
        const res = jobTemp.find((item) => item.coidassignedjob === text)
        return res ? res.cname : text
      },
    },
    {
      title: '降级前职级',
      dataIndex: 'jobLevelId',
      hideInSearch: true,
      render: (text) => {
        const res = jobLevel.find((item) => item.id === text);
        return res ? res.name : text
      },
    },
    {
      title: '降级后职级',
      dataIndex: 'afterJobLevelId',
      key: 'afterJobLevelId',
      width: 150,
      render: (text, record) => {
        if (record.editable) {
          return (
            <Select placeholder="请选择" value={text}
                    onChange={(e) => handleFieldChange(e, 'afterJobLevelId', record.key)}>
              {tempJobLevel?.map((item, index) => {
                return (
                  <Option value={`${item.id}`} key={item.id}>
                    {item.name}
                  </Option>
                )
              })}
            </Select>
          )
        }
        const res = jobLevel.find((item) => item.id === text)
        return res ? res.name : text
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 110,
      fixed: 'right',
      render: (text, record) => {
        if (!!record.editable && loading) {
          return null
        }
        if (record.editable) {
          return (
            <span>
              <a onClick={(e) => updateRow(e, record.key, record.oid)}>保存</a>
              <Divider type="vertical"/>
              <a onClick={(e) => cancel(e, record.key)}>取消</a>
            </span>
          )
        }
        return (
          <span>
            <a onClick={(e) => toggleEditable(e, record.key)}>编辑</a>
            <Divider type="vertical"/>
            <Popconfirm title="是否要删除此行？" cancelText='取消' okText='确认' onConfirm={(e) => remove(e, record.key)}>
              <a>删除</a>
            </Popconfirm>
          </span>
        )
      },
    },
  ]
  return (
    <>
      <Table
        loading={loading}
        columns={columns}
        dataSource={data}
        pagination={false}
        rowClassName={(record) => (record.editable ? styles.editable : '')}
        scroll={{x:1000}}
      />
    </>
  )
}

export default connect(({recruitment}) => ({
  recruitment,
}))(TableForm)

